<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t(title)" :v-if="dialogVisible" :visible.sync="dialogVisible" :width="lang === 'zh'?'620px':'710px'" top='5vh' @close='close'>
    <div class="dialogContentBox">
      <el-form ref="form" :model="record" :label-width="lang==='zh'?'70px':'120px'" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('名称')" prop="name">
          <el-input v-emoji v-model="record.name" id="strategy-multiDialog-name" ref="recordName" style="width:220px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('类型')" prop="type">
          <span>{{$t('多出口模式')}}</span>
        </el-form-item>
        <el-form-item label="IPv4/IPv6" prop="ip">
          <el-radio v-model="record.ip" class="ipv4" label="ipv4">IPv4</el-radio>
          <el-radio v-model="record.ip" class="ipv6" label="ipv6">IPv6</el-radio>
        </el-form-item>
        <el-form-item :label="$t('负载类型')" prop="balance">
          <el-select v-model="record.balance" ref="balance" :placeholder="$t('请选择')" size='small' filterable style="width:220px;">
            <el-option v-for="(item, key) in balanceList"  :id="`strategy-multiDialog-balance${key}`" :key="key" :label="item" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('状态')" prop="status">
          <el-radio v-model="record.status" class="able" label="able">{{$t('开启')}}</el-radio>
          <el-radio v-model="record.status" class="disables" label="disable">{{$t('关闭')}}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('出接口')" prop="dev">
          <el-select v-model="record.dev" style="width:220px;" :placeholder="$t('请选择出接口')" multiple size='small' ref="recordDev" clearable collapse-tags filterable>
            <el-option v-for="(item,index) in physicalList" :id="`strategy-multiDialog-dev${index}`"  :disabled="item.enPortMode === 3" :key="item.strPhysicsName" :label="item.strPhysicsName" :value="item.strPhysicsName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('源IP')" prop="src">
          <el-select v-model="record.src" ref="recordSrc" :placeholder="$t('请选择')" size='small' style="width:220px;" filterable clearable>
            <el-option v-for="(item,index) in filMac(srcList)" :key="item.id" :id="`strategy-multiDialog-src${index}`" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <addr-dialog @commandList='commandList' :nameType='"src"'></addr-dialog>
        </el-form-item>
        <el-form-item :label="$t('目的IP')" prop="dst">
          <el-select v-model="record.dst" ref="recordDst" :placeholder="$t('请选择')" size='small' style="width:220px;" filterable clearable>
            <el-option v-for="(item,index) in filMac(dstList)" :id="`strategy-multiDialog-dst${index}`" :key="item.id" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <addr-dialog @commandList='commandList' :nameType='"dst"'></addr-dialog>
        </el-form-item>
        <el-form-item :label="$t('服务')" prop="ser">
          <el-select v-model="record.ser" ref="recordSer" :placeholder="$t('请选择')" size='small' style="width:220px;" filterable clearable>
            <el-option v-for="(item,index) in iservicepsList"  :id="`strategy-multiDialog-ser${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <ServerDialog @serviceList='serviceList'></ServerDialog>
        </el-form-item>
        <el-form-item :label="$t('应用')" prop="app">
          <el-select v-model="record.app" ref="recordApp" :placeholder="$t('请选择')" size='small' style="width:220px;" filterable clearable>
            <el-option v-for="(item,index) in appList" :id="`strategy-multiDialog-app${index}`" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <AppDialog @appDataList='appDataList'></AppDialog>
        </el-form-item>
        <el-form-item :label="$t('描述')" prop="desc">
          <el-input v-emoji v-model="record.desc"  id="strategy-multiDialog-desc" ref="desc" style="width:220px;" size='small' :autosize="{ minRows: 4 }" type="textarea" @keydown.native="handleKeyCode($event)"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getPhysicalApiArray } from '@/api/network/api/physical'
import { addMultiInfo, editMultiInfo } from '@/api/network/route/policyRoute'
import { getAddrGroupArray } from '@/api/list/addr-group'
import { getAddrArray } from '@/api/list/addr'
import { getServiceArray, getServiceReArray } from '@/api/list/server'
import { getAppArray, getAppReArray } from '@/api/list/app'
import addrDialog from './AddrDialog'
import ServerDialog from './ServerDialog'
import AppDialog from './AppDialog'
import { texttextClass, selectClass, inputClass } from '@/utils/input-class.js'
export default {
  name: 'StrategyMultiDialog',
  components: {
    addrDialog,
    ServerDialog,
    AppDialog
  },
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateDev = (rule, value, callback) => {
      if (!String(value).trim() || value.length < 1) {
        callback(new Error(this.$t('请选择出接口')))
      } else if (value.length < 2) {
        callback(new Error(this.$t('输入的接口数，低于最小值，2')))
      } else {
        callback()
      }
    }
    return {
      lang: this.$i18n.locale,
      dialogVisible: false,
      record: {
        id: null,
        name: '',
        old_name: '',
        type: 'multi',
        ip: 'ipv4',
        status: 'able',
        balance: 'round',
        dev: [],
        src: '',
        dst: '',
        ser: '',
        app: '',
        desc: ''
      },
      recordCopy: {
        id: null,
        name: '',
        old_name: '',
        type: 'multi',
        ip: 'ipv4',
        status: 'able',
        balance: 'round',
        dev: [],
        src: '',
        dst: '',
        ser: '',
        app: '',
        desc: ''
      },
      lang: this.$i18n.locale,
      title: '',
      balanceList: {
        'round': this.$t('轮询负载'),
        'width': this.$t('带宽负载'),
        'super': this.$t('最优路径')
      },
      physicalList: [],
      srcList: [],
      dstList: [],
      iservicepsList: [],
      appList: [],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        balance: [{ required: false, validator: validateName, trigger: 'blur' }],
        dev: [{ required: false, validator: validateDev, trigger: 'change' }]
      }
    }
  },
  watch: {
    'record.desc': {
      handler (newVal) {
        this.record.desc = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    filMac(list=[]) {
      return list.filter(item => item.ip_type !== 7)
    },
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['recordName', 'recordDev']
        const textdata = ['desc']
        const selectData = ['balance', 'recordSrc', 'recordDst', 'recordSer', 'recordApp']
        selectClass(this.$refs, selectData)
        texttextClass(this.$refs, textdata)
        inputClass(this.$refs, data)
      })
      this.title = data ? this.$t('编辑') : this.$t('添加')
      if (data) {
        this.record.old_name = data.name
        this.record = Object.assign(this.record, data)
        this.record.status = data.state
        this.record.dev = []
        for (let item of data['mutil-dev']) {
          this.record.dev.push(item.dev)
        }
      }
      this.physicalApiArray()
      this.commandList()
      this.serviceList()
      this.appDataList()
    },
    submit () {
      if (!this.record.id) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            addMultiInfo(this.record).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('添加成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          }
        })
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            editMultiInfo(this.record).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('编辑成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          }
        })
      }
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.physicalList = []
      this.srcList = []
      this.dstList = []
      this.iservicepsList = []
      this.appList = []
      this.$refs.form.resetFields()
    },
    physicalApiArray () {
      this.physicalList = []
      getPhysicalApiArray().then(response => {
        if (response.status === 0) {
          this.physicalList = response.info
        }
      })
    },
    commandList (data, nameType, name) {
      this.srcList = []
      this.dstList = []
      getAddrArray().then(response => {
        if (response.status === 0) {
          getAddrGroupArray().then(res => {
            if (res.status === 0) {
              // this.srcList = response.info.concat(res.info)
              // this.dstList = response.info.concat(res.info)
              for (let item of response.info) {
                item.nameShow = this.$t('地址-') + item.name
                this.srcList.push(item)
                this.dstList.push(item)
              }
              for (let item of res.info) {
                item.nameShow = this.$t('地址组-') + item.name
                this.srcList.push(item)
                this.dstList.push(item)
              }
            }
          })
        }
      })
      if (data && nameType === 'src') {
        this.record.src = name
      } else if (data && nameType === 'dst') {
        this.record.dst = name
      }
    },
    serviceList (data) {
      this.iservicepsList = []
      getServiceArray().then(response => {
        if (response.status === 0) {
          getServiceReArray().then(res => {
            if (res.status === 0) {
              this.iservicepsList = response.info.concat(res.info)
            }
          })
        }
      })
      if (data) {
        this.record.ser = data.name
      }
    },
    appDataList () {
      this.appList = []
      getAppArray().then(response => {
        if (response.status === 0) {
          getAppReArray().then(res => {
            if (res.status === 0) {
              this.appList = response.info.concat(res.info)
            }
          })
        }
      })
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>
<style scoped>
.dialogContentBox {
  max-height: calc(90vh - 184px);
  overflow-y: auto;
}
</style>
